<template>
  <div v-if="show" class="excel-container">
    <!-- Excel编辑器模态框 -->
    <ExcelEditor
      v-model:show="showExcelEditor"
      :templateId="currentTemplate.id"
      :fileName="currentTemplate.ruleFileName"
      @save-success="handleSaveSuccess"
      @close="handleEditorClose"
    />
    <div class="excel-header">
      <h2 class="excel-title">规则模板列表</h2>
      <button class="btn-secondary" @click="goBack">
        <i class="fas fa-arrow-left"></i> 返回主界面
      </button>
    </div>
    
    <div class="table-container">
      <div v-if="loading" class="loading-indicator">
        <i class="fas fa-spinner fa-spin"></i> 加载中...
      </div>
      
      <div v-else-if="error" class="error-message">
        <i class="fas fa-exclamation-circle"></i> {{ error }}
        <button class="btn-primary retry-btn" @click="fetchTemplateList">重试</button>
      </div>
      
      <table v-else class="template-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>模板文件名</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="template in templateList" :key="template.id">
            <td>{{ template.id }}</td>
            <td>{{ template.ruleFileName }}</td>
            <td>{{ formatDate(template.createTime) }}</td>
            <td>
              <button 
                class="btn-action" 
                @click="downloadTemplate(template.id)"
                :disabled="downloadStatus[template.id] === 'loading'"
              >
                <i :class="[
                  downloadStatus[template.id] === 'loading' ? 'fas fa-spinner fa-spin' : 
                  downloadStatus[template.id] === 'success' ? 'fas fa-check' : 
                  downloadStatus[template.id] === 'error' ? 'fas fa-exclamation-circle' : 
                  'fas fa-download'
                ]"></i> 
                {{ 
                  downloadStatus[template.id] === 'loading' ? '下载中' : 
                  downloadStatus[template.id] === 'success' ? '已下载' : 
                  downloadStatus[template.id] === 'error' ? '失败' : 
                  '下载' 
                }}
              </button>
              <!-- <button 
                class="btn-action"
                @click="handleEdit(template)"
              >
                <i class="fas fa-edit"></i> 编辑
              </button>-->
              <button 
                class="btn-action btn-danger" 
                @click="confirmDelete(template.id)"
              >
                <i class="fas fa-trash"></i> 删除
              </button> 
            </td>
          </tr>
          <tr v-if="templateList.length === 0">
            <td colspan="4" class="no-data">暂无规则模板数据</td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- <div class="excel-actions">
      <button class="btn-primary">
        <i class="fas fa-plus"></i> 新建模板
      </button>
    </div> -->
  </div>
</template>

<script setup lang="ts">
import { useRuleTemplateManagement } from '../scripts/ruleTemplateManagement'
import ExcelEditor from './ExcelEditor.vue'
import { ref, watch } from 'vue'

const props = defineProps<{
  show: boolean
}>()

const emit = defineEmits<{
  'update:show': [value: boolean]
}>()

watch(() => props.show, (newVal) => {
  if (newVal) {
    fetchTemplateList()
  }
})

// Excel编辑器相关状态
const showExcelEditor = ref(false)
const currentTemplate = ref<{ id: string; ruleFileName: string }>({ id: '', ruleFileName: '' })


// 处理保存成功
const handleSaveSuccess = () => {
  try {
    alert('保存成功！')
    fetchTemplateList() // 刷新列表
  } catch (error) {
    console.error('刷新列表失败:', error)
    alert('保存成功，但刷新列表失败，请手动刷新页面')
  }
}

// 监听编辑器关闭
const handleEditorClose = () => {
  currentTemplate.value = { id: '', ruleFileName: '' }
  showExcelEditor.value = false
}

const {
  templateList,
  loading,
  error,
  downloadStatus,
  fetchTemplateList,
  downloadTemplate,
  formatDate,
  deleteTemplate
} = useRuleTemplateManagement()

const confirmDelete = async (templateId: string) => {
  if (!confirm('确定要删除这个模板吗？此操作不可恢复。')) {
    return
  }
  
  const success = await deleteTemplate(templateId)
  if (success) {
    alert('模板删除成功')
  } else {
    alert('模板删除失败，请重试')
  }
}

const goBack = () => {
  emit('update:show', false)
}
</script>

<style scoped>
.excel-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #f8f9fa;
  z-index: 1000;
  padding: 20px;
  overflow-y: auto;
}

.excel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.excel-title {
  font-size: 24px;
  color: #333;
}

.table-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.template-table {
  width: 100%;
  border-collapse: collapse;
}

.template-table th,
.template-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.template-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.template-table tr:hover {
  background-color: #f8f9fa;
}

.btn-action {
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  padding: 6px 10px;
  margin-right: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.btn-action:hover {
  background-color: #e0e0e0;
}

.btn-danger {
  color: #dc3545;
}

.btn-danger:hover {
  background-color: #ffebee;
}

.loading-indicator {
  padding: 30px;
  text-align: center;
  color: #666;
  font-size: 16px;
}

.error-message {
  padding: 30px;
  text-align: center;
  color: #dc3545;
  font-size: 16px;
}

.retry-btn {
  margin-left: 10px;
  padding: 6px 12px;
}

.no-data {
  text-align: center;
  color: #666;
  padding: 30px;
}

.excel-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>